package com.cll.mall.product.service.impl;

import com.cll.mall.product.service.CategoryBrandRelationService;
import com.cll.mall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cll.common.utils.PageUtils;
import com.cll.common.utils.Query;

import com.cll.mall.product.dao.CategoryDao;
import com.cll.mall.product.entity.CategoryEntity;
import com.cll.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类以及子分类，以树形结构组装起来
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2.组装成父子树形结构
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    /**
     * 批量删除
     *
     * @param list
     */
    @Override
    public void removeMenuByIds(List<Long> list) {
        // TODO 1.检查当前删除的菜单，是否被其他地方引用
        baseMapper.deleteBatchIds(list);

    }

    @Override
    public Long[] getPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        // 递归查询父类
        paths = findParentPath(catelogId, paths);
        // 逆序，父在前
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    /**
     * 根据catelogId查询所有父分类ID
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        // 递归查询父类
        paths = findParentPath(catelogId, paths);
        // 逆序，父在前
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {

        List<CategoryEntity> entities = baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;

    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        // 1.查出所有1 级分类
        List<CategoryEntity> level1Categorys = getLevel1Categorys();

        // 2.封装成树形结构
        Map<String, List<Catelog2Vo>> result = level1Categorys.stream().collect(
                Collectors.toMap(
                        k -> k.getCatId().toString(),
                        v -> {
                            //1.获取二级分类
                            List<CategoryEntity> categoryEntities = baseMapper.selectList(
                                    new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
                            //2.封装成vo
                            List<Catelog2Vo> catelog2Vos = null;
                            if (categoryEntities != null && !categoryEntities.isEmpty()) {
                                catelog2Vos = categoryEntities.stream().map(l2 -> {
                                    Catelog2Vo catelog2Vo =
                                            new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                                    //1.获取三级分类
                                    List<CategoryEntity> level3Categorys = baseMapper.selectList(
                                            new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                                    if (level3Categorys != null && !level3Categorys.isEmpty()) {
                                        catelog2Vo.setCatalog3List(level3Categorys.stream().map(l3 ->
                                                new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName())
                                        ).collect(Collectors.toList()));
                                    }
                                    return catelog2Vo;
                                }).collect(Collectors.toList());
                            }
                            return catelog2Vos;
                        }));
        return result;
    }

    /**
     * 级联更新所有关联表的冗余数据
     * 缓存策略：失效模式，方法执行完删除缓存
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            // 更新冗余表
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
            // TODO 更新其他冗余表
        }
    }

    /**
     * 递归查找父路径
     */
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity category = this.getById(catelogId);
        if (category.getParentCid() != 0) {
            findParentPath(category.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找子菜单
     *
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}